package com.sidianzhong.sdz.utils;

import java.io.*;
import java.net.Socket;

public class SocketClient {

    private static String open = "{\"messageType\":\"APPCMD\",\"messageKey\":\"1565837652699\",\"equipmentType\":\"8\",\"equipmentKey\":\"1\",\"operatingType\":\"1\",\"operatingMessage\":[{\"SetType\":\"4\",\"SetParam\":\"1\"}]}";
    private static String close = "{\"messageType\":\"APPCMD\",\"messageKey\":\"1565837652699\",\"equipmentType\":\"8\",\"equipmentKey\":\"1\",\"operatingType\":\"1\",\"operatingMessage\":[{\"SetType\":\"4\",\"SetParam\":\"2\"}]}";

    public static void main(String[] arga) {
        new Thread(() -> {
            SocketServer.isOpen = true;
            sendMessage(open);
            try {
                Thread.sleep(60 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            sendMessage(close);
        }).start();
    }

    public static void sendMessage(String json) {
        OutputStream outputStream = null;
        Socket socket = null;
        try {
            socket = new Socket("127.0.0.1", 6667);
            outputStream = socket.getOutputStream();
            int num = json.length();
            byte[] bytes = new byte[4];
            bytes[3] = (byte) ((num >> 24) & 0xff);
            bytes[2] = (byte) ((num >> 16) & 0xff);
            bytes[1] = (byte) ((num >> 8) & 0xff);
            bytes[0] = (byte) (num & 0xff);
            outputStream.write(bytes);
            outputStream.write(json.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }
}